package com.oscar.ehome.view.pageview;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oscar.ehome.Manifest;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.pagebean.HuokeBean;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.AesUtils;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.makeTime;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by juxing
 * author: MengWanhe
 * date: On 2017/10/12
 * 游戏详情
 */

public class HuokeDetailActivity extends BasesActivity {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /***
     * 分享
     */
    @BindView(R.id.title_img_right)
    ImageView titleImgRight;
    /**
     * 分享
     */
    @BindView(R.id.title_right_layput)
    RelativeLayout titleRightLayput;
    /**
     *
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    /**
     * web view
     */
    @BindView(R.id.huoke_webview)
    WebView huokeWebview;

    Map<String, String> map = new HashMap<String, String>();
    HuokeBean.HuokeListBean bean;
    String context = "";
    String url = "";
    String token = "";
    String id = "";
    String time = "";

    //分享
    private ShareAction shareAction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huokedetail);
        ButterKnife.bind(this);
        initView();
        initData();
        addView();
    }

    /**
     * 初始化
     */
    public void initView() {
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(HuokeDetailActivity.this).getSystemConfig().getColor()));
        titleImgBack.setVisibility(View.VISIBLE);
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleRightLayput.setVisibility(View.VISIBLE);
        titleImgRight.setVisibility(View.VISIBLE);
        titleImgRight.setImageResource(R.mipmap.fenxiang);
    }

    /**
     *
     */
    public void initData() {
        context = getIntent().getStringExtra("context");
        if (context != null && !"".equals(context)) {
            bean = new Gson().fromJson(context, HuokeBean.HuokeListBean.class);
        }
        if (bean != null) {
            id = bean.getId();
            titleTopbar.setText(bean.getGamesTheme());
        }
        token = SystemConfigFactory.getInstance(HuokeDetailActivity.this).getSystemConfig().getToken();
        String mtime = makeTime.mtime();
        try {
            time = AesUtils.encryptAES(mtime, "1234567812345678");
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        map.put("id", id);
        map.put("token", token);
        map.put("timestamp", time);

        url = CommonUtils.getUrl(C.huokedetail_url, map);
    }

    /**
     * 展示网页
     */
    public void addView() {
        huokeWebview.loadUrl(url);
        // WebView加载web资源
        com.tencent.smtt.sdk.WebSettings webSettings = huokeWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        huokeWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("tel:")) {
                    String mobile = url.substring(url.lastIndexOf(":") + 1);
                    Intent intent_kefu = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + mobile);
                    intent_kefu.setData(data);
                    startActivity(intent_kefu);
                }else {
                    view.loadUrl(url);
                }




                return true;
            }
        });
    }


    @OnClick({R.id.title_layout_left, R.id.title_right_layput})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_layout_left://返回
                if (huokeWebview.canGoBack()) {
                    huokeWebview.goBack();//返回上个页面
                } else {
                    finish();
                }
                break;
            case R.id.title_right_layput://分享
                openShare();
                break;
        }
    }

    /**
     * 打开分享面板
     */
    public void openShare() {
        UMImage thumb = new UMImage(HuokeDetailActivity.this, R.mipmap.ehomelogo);
        shareAction = new ShareAction(HuokeDetailActivity.this)
                .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .withMedia(new UMWeb(bean.getUrl(),bean.getGamesTheme(),
                        bean.getRemarks(), thumb))
                .setCallback(umShareListener);
        shareAction.open();
    }

    private UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(HuokeDetailActivity.this, "分享成功", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (t.getMessage().contains("2008")) {
                Toast.makeText(HuokeDetailActivity.this, "分享失败,请检查是否安装应用！", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(HuokeDetailActivity.this, "分享失败", Toast.LENGTH_LONG).show();
            }
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(HuokeDetailActivity.this, "分享取消", Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
//        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
//        if (ssoHandler != null) {
////            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }


    /**
     * 使点击回退按钮不会直接退出整个应用程序而是返回上一个页面
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && huokeWebview.canGoBack()) {
            huokeWebview.goBack();//返回上个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
